#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "hiredisutils.h"

redisContext *globalRedisCtx;
char redisError[201];

void redisShowReply(redisReply* reply, int deep)
{
        int i = 0;
        char margin[100];

        memset(margin, 0x00, sizeof(margin));
        for (i = 0; i < deep; i++) {
                strcat(margin, "\t");
        }

        if (reply->type == REDIS_REPLY_STRING) {
                printf("%s", margin);
                printf("STRING:[%s]\n", reply->str);
        }
        else if (reply->type == REDIS_REPLY_ARRAY) {
                printf("%s", margin);
                printf("ARRAY TYPE\n");
                int j = 0;
                for (j = 0; j < reply->elements; j++) {
                        printf("%sarr[%d]", margin, j);
                        redisShowReply(reply->element[j], deep + 1);
                }
        }
        else if (reply->type == REDIS_REPLY_INTEGER) {
                printf("%s", margin);
                printf("INTEGER TYPE:[%lld]\n", reply->integer);
        }
        else if (reply->type == REDIS_REPLY_NIL) {
                printf("%s", margin);
                printf("NIL TYPE\n");
        }
        else if (reply->type == REDIS_REPLY_STATUS) {
                printf("STATUS TYPE:[%lld]\n", reply->integer);
        }
        else if (reply->type == REDIS_REPLY_ERROR) {
                printf("ERROR TYPE:[%s]\n", reply->str);
        }
}

redisContext* redis_connect(char *ip, int port)
{
	redisContext *c = NULL;
	struct timeval timeout = { 3, 000000 }; // 3.0 seconds
	char host[51];

	memset(host, 0x00, sizeof(host));
	if (ip) {
		strcpy(host, ip);
	}
	else {
		strcpy(host, "127.0.0.1");
	}

	c = redisConnectWithTimeout(host, port, timeout);
	if (c == NULL || c->err) {
		if (c) {
			redisFree(c);
			c = NULL;
			
			return NULL;
		} 
		else {
			return NULL;
		}
	}

	globalRedisCtx = c;

	return c;
}

redisReply* redis_command(char *commandBuf)
{
        redisReply *reply = NULL;

        reply = redisCommand(globalRedisCtx, commandBuf);
	if (reply->type == REDIS_REPLY_ERROR) {
		strcpy(redisError, reply->str);
		freeReplyObject(reply);

		return NULL;
	}
	
	return reply;
}

/* like hset command, value field can't have space */
redisReply* redis_command_v(char *fmt, ...)
{
        redisReply *reply = NULL;

	va_list ap;
	va_start(ap, fmt);

        reply = redisvCommand(globalRedisCtx, fmt, ap);
        if (reply->type == REDIS_REPLY_ERROR) {
                strcpy(redisError, reply->str);
                freeReplyObject(reply);
		va_end(ap);

                return NULL;
        }

	va_end(ap);

        return reply;
}
